<?php

class Controller_Admin_Merchmanagement_Inventory extends Controller_Admin_Template {
	
	const INDEX_PAGE = 'admin/merchmanagement/inventory';
	
	public function before() {
		parent::before();
		
		$this->template->title = __('Inventory Management');
	}
	
	public function action_index() {
		$category_id = $this->request->param('id');
		
		$root_categories = ORM::factory('category')
			->where('parent_category_id', '=', 0)
			->order_by('name', 'asc')
			->find_all();
		
		$view = View::factory('admin/merchmanagement/inventory/index');
		$view->set('root_categories', $root_categories);
		
		$this->template->title = __('Inventory Management');	
		$this->template->content = $view;
	}
	
	public function action_edit() {
		$category_id = $this->request->param('id');
		$view = View::factory('admin/merchmanagement/inventory/edit');
		
		$category = ORM::factory('category', $category_id);
		$attributes = $category->attributes->find_all();
		$inv_items = array();
		$items = $category->items->where('discontinued', '=', 0)->order_by('name', 'asc')->find_all();
		foreach($items as $item):
			$inv_items[] = ORM::factory('inventoryitem')
				->where('item_id', '=', $item->id)->find_all();
		endforeach;
		$view->set('category', $category);
		$view->set('attributes', $attributes);
		$view->set('inv_items', $inv_items);
		$view->bind('errors', $errors);

		if($_POST) {
			// need to add user id to order
			$order = ORM::factory('restockorder');
			$order->inventoryitem_id = $_POST['inventoryitem_id'];
			$order->quantity = $_POST['quantity'];
			$order->unit_price = $_POST['restock_price'];
			$order->total_price = $_POST['quantity'] * $_POST['restock_price'];
			try{
				$order->save();
				$inventory_item = ORM::factory('inventoryItem', $order->inventoryitem_id);
				$inventory_item->quantity += $order->quantity;
				$inventory_item->save();
				$this->request->redirect('admin/merchmanagement/inventory/edit/'.$category->id);
			}
			catch(ORM_Validation_Exception $e) {
				$errors = $e->errors('models');
			}
			
		}
		
		$this->template->content = $view;
		
	}
	
	public function action_update() {
		$inv_item_id = $this->request->param('id');
		$inv_item = ORM::factory('inventoryItem', $inv_item_id);
		$inv_item->quantity = $_POST['quantity'];
		$inv_item->save();
		$category_id = $inv_item->item->category->id;
		
		$this->request->redirect(self::INDEX_PAGE.'/edit/'.$category_id);
	}
}